package com.atguigu.spzx.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.contant.RedisConstant;
import com.atguigu.spzx.model.entity.system.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        if("OPTIONS".equals(method)) return true;

        String token = request.getHeader("token");
        // 没有获取到token
        if(StringUtils.isEmpty(token)){
            responseNoLoginInfo(response);
            return false;
        }

        String sysUserJson = redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_PREFIX + token);
        // 没登录
        if(StringUtils.isEmpty(sysUserJson)){
            responseNoLoginInfo(response);
            return false;
        }

        // 将用户信息存到ThreadLocal
        SysUser sysUser = JSON.parseObject(sysUserJson, SysUser.class);
        AuthContextUtil.set(sysUser);

        // 重置Redis中的用户的有效时间
        redisTemplate.expire(RedisConstant.USER_LOGIN_PREFIX + token, 30, TimeUnit.MINUTES);

        return true;
    }

    private void responseNoLoginInfo(HttpServletResponse response){
        Result<Object> result = Result.build(null, 208,"用户未登录");
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
